package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.cache.CategoryCache;
import com.tianji.api.client.course.CatalogueClient;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.client.remark.RemarkClient;
import com.tianji.api.client.search.SearchClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.course.CataSimpleInfoDTO;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.QuestionFormDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.PlanStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.LearningLessonMapper;
import com.tianji.learning.query.QuestionAdminPageQuery;
import com.tianji.learning.query.QuestionPageQuery;
import com.tianji.learning.service.IInteractionQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.learning.service.IInteractionReplyService;
import com.tianji.learning.vo.QuestionAdminVO;
import com.tianji.learning.vo.QuestionVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动提问的问题表 服务实现类
 * </p>
 *
 * @author leiyuhang
 * @since 2023-07-27
 */
@Service
@RequiredArgsConstructor
public class InteractionQuestionServiceImpl extends ServiceImpl<InteractionQuestionMapper, InteractionQuestion> implements IInteractionQuestionService {
    private  final UserClient userClient;
    private  final IInteractionReplyService replyService;
    private  final SearchClient searchClient;
    private  final CourseClient courseClient;
    private  final CatalogueClient catalogueClient;
    private  final CategoryCache categoryCache;
    private  final RemarkClient remarkClient;
    @Override
    public void saveQuestion(QuestionFormDTO questionDTO) {
        Long user = UserContext.getUser();
        InteractionQuestion question = BeanUtils.copyBean(questionDTO, InteractionQuestion.class);
        question.setUserId(user);
        save(question);
    }

    @Override
    public void editQuestion(QuestionFormDTO questionDTO) {
        Long user = UserContext.getUser();
        InteractionQuestion question = BeanUtils.copyBean(questionDTO, InteractionQuestion.class);
        question.setUserId(user);
        updateById(question);
    }

    @Override
    public PageDTO<QuestionVO> queryQuestionPage(QuestionPageQuery query) {
        if (query.getCourseId()== null && query.getSectionId()==null){
            throw  new BadRequestException("课程id和小结id不能为空");
        }
        Page<InteractionQuestion> page = lambdaQuery().eq(query.getOnlyMine(), InteractionQuestion::getUserId, UserContext.getUser())
                .eq(query.getCourseId() != null, InteractionQuestion::getCourseId, query.getCourseId())
                .eq( query.getSectionId()!=null,InteractionQuestion::getSectionId, query.getSectionId())
                .eq(InteractionQuestion::getHidden,false)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = page.getRecords();
        if (CollUtils.isEmpty(records)){
            return PageDTO.empty(page);
        }
        List<QuestionVO> list = new ArrayList<>();
        for (InteractionQuestion questionVO : records) {
            QuestionVO vo = BeanUtils.copyBean(questionVO,QuestionVO.class);
            if (!questionVO.getAnonymity()){
                UserDTO userDTO = userClient.queryUserById(questionVO.getUserId());
                if (userDTO!=null){
                    vo.setUserName(userDTO.getName());
                    vo.setUserIcon(userDTO.getIcon());
                }}
                InteractionReply one = replyService.lambdaQuery().eq(InteractionReply::getId, questionVO.getLatestAnswerId())
                        .one();
                if (one!=null){
                    vo.setLatestReplyContent(one.getContent());
                    UserDTO user = userClient.queryUserById(one.getUserId());
                    vo.setLatestReplyUser(user.getName());
                }
            list.add(vo);
        }

        return PageDTO.of(page,list);
    }

    @Override
    public QuestionVO queryQuestionById(Long id) {
        InteractionQuestion question = getById(id);
        if(question == null || question.getHidden()){
            // 没有数据或者是被隐藏了
            return null;
        }
        UserDTO userDTO= null;
        if (!question.getAnonymity()){
           userDTO= userClient.queryUserById(question.getUserId());
        }
        QuestionVO vo = BeanUtils.copyBean(question,QuestionVO.class);
        if (userDTO != null){
            vo.setUserIcon(userDTO.getIcon());
            vo.setUserName(userDTO.getName());
        }
        List<Long> list = new ArrayList<>();
        list.add(id);

        return  vo;
    }

    @Override
    public void deleteById(Long id) {
        //1.查询登录用户的id
        //2.根据问题id删除问题
        removeById(id);
        //3.根据问题id删除问题的回答
        replyService.deleteById(id);
    }

    @Override
    public void changeHidden(Long id, Boolean hidden) {
        InteractionQuestion question= getById(id);
        if (question == null){
             return;
        }
        InteractionQuestion i = new InteractionQuestion();
        i.setId(id);i.setHidden(hidden);
        updateById(i);
        List<InteractionReply> list = replyService.lambdaQuery().eq(InteractionReply::getQuestionId, i.getId()).list();
        if (CollUtils.isEmpty(list)){
            return;
        }
        for (InteractionReply interactionReply : list) {
            interactionReply.setHidden(hidden);

        }replyService.updateBatchById(list);

    }

    @Override
    public QuestionAdminVO checkQuestionAdmin(Long id) {
        InteractionQuestion question = getById(id);
        if(question == null || question.getHidden()){
            // 没有数据或者是被隐藏了
           return  null;
        }
        UserDTO userDTO= null;
        if (!question.getAnonymity()){
            userDTO= userClient.queryUserById(question.getUserId());
        }
        QuestionAdminVO vo = BeanUtils.copyBean(question,QuestionAdminVO.class);
        if (userDTO != null){
            vo.setUserName(userDTO.getName());
        }
        CourseFullInfoDTO courseInfoById = courseClient.getCourseInfoById(question.getCourseId(),false,false);
        List<UserDTO> userDTOS = userClient.queryUserByIds(courseInfoById.getTeacherIds());
        String collect = userDTOS.stream().map(UserDTO::getName).collect(Collectors.joining("/"));
        vo.setTeacherName(collect);
        vo.setStatus(1);
        String categoryNames = categoryCache.getCategoryNames(courseInfoById.getCategoryIds());
        vo.setCategoryName(categoryNames);
        UserDTO userDTO1 = userClient.queryUserById(question.getUserId());
        vo.setUserName(userDTO1.getName());
        return  vo;
    }

    @Override
    public PageDTO<QuestionAdminVO> queryQuestionPageAdmin(QuestionAdminPageQuery query) {
        //1.处理课程id，获取课程名称
        List<Long> courseIds = null;
        if (StringUtils.isNotBlank(query.getCourseName())) {
            courseIds = searchClient.queryCoursesIdByName(query.getCourseName());
            if (CollUtils.isEmpty(courseIds)) {
                return PageDTO.empty(0L, 0L);
            }
        }
        //2.分页查询
        Integer status = query.getStatus();
        LocalDateTime beginTime = query.getBeginTime();
        LocalDateTime endTime = query.getEndTime();
        Page<InteractionQuestion> page = lambdaQuery().in(courseIds != null, InteractionQuestion::getCourseId, courseIds)
                .eq(status != null, InteractionQuestion::getStatus, status)
                .gt(beginTime != null, InteractionQuestion::getCreateTime, beginTime)
                .lt(endTime != null, InteractionQuestion::getCreateTime, endTime)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        //3.查询数据
        Set<Long> uIds = new HashSet<>();
        Set<Long> cIds = new HashSet<>();
        Set<Long> cateIds = new HashSet<>();
        for (InteractionQuestion record : records) {
            uIds.add(record.getUserId());
            cIds.add(record.getCourseId());
            cateIds.add(record.getSectionId());
        }
        List<UserDTO> userDTOS = userClient.queryUserByIds(uIds);
        Map<Long,UserDTO> userMap = new HashMap<>(userDTOS.size());
        if (CollUtils.isNotEmpty(userDTOS)) {
            userMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, u -> u));
        }
        List<CourseSimpleInfoDTO> simpleInfoList = courseClient.getSimpleInfoList(cIds);
        Map<Long,CourseSimpleInfoDTO> cMap = new HashMap<>(simpleInfoList.size());
        if (CollUtils.isNotEmpty(simpleInfoList)) {
            cMap = simpleInfoList.stream().collect(Collectors.toMap(CourseSimpleInfoDTO::getId,c->c));
        }
        List<CataSimpleInfoDTO> catas = catalogueClient.batchQueryCatalogue(cateIds);
        Map<Long, String> cataMap = new HashMap<>(catas.size());
        if (CollUtils.isNotEmpty(catas)) {
            cataMap = catas.stream()
                    .collect(Collectors.toMap(CataSimpleInfoDTO::getId, CataSimpleInfoDTO::getName));
        }
        //4.封装vo
        List<QuestionAdminVO> voList = new ArrayList<>();
        for (InteractionQuestion record : records) {
            QuestionAdminVO vo = BeanUtils.copyBean(record,QuestionAdminVO.class);
            UserDTO userDTO = userMap.get(record.getUserId());
            if (userDTO != null) {
                vo.setUserName(userDTO.getName());
            }
            CourseSimpleInfoDTO cInfo = cMap.get(record.getCourseId());
            if (cInfo != null) {
                vo.setCourseName(cInfo.getName());
                vo.setCategoryName(categoryCache.getCategoryNames(cInfo.getCategoryIds()));
            }
            vo.setChapterName(cataMap.getOrDefault(record.getChapterId(), ""));
            vo.setSectionName(cataMap.getOrDefault(record.getSectionId(), ""));
            voList.add(vo);
        }
        return PageDTO.of(page,voList);
    }
}
